﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Device.Location;
using System.Windows.Threading;

namespace Strava1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadCache();
                DataContext = App.ViewModel;
            }

            ridesLB.SelectionChanged += new SelectionChangedEventHandler(Rides_SelectionChanged);
            alertsLB.SelectionChanged += new SelectionChangedEventHandler(Alerts_SelectionChanged);

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Rides_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                NavigationService.Navigate(new Uri("/RideDetails.xaml?id=" + ((Ride)e.AddedItems[0]).Id, UriKind.Relative));
            }
            ((ListBox)sender).SelectedIndex = -1;
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //App.ViewModel.MySegments = new ObservableCollection<Segment>(App.ViewModel.MySegments.Distinct());
        }

        private void Settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            App.ViewModel.LoadData();
        }

        private void ClearCache_Click(object sender, EventArgs e)
        {
            App.ViewModel.ClearCache();
        }

        private void Segments_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                NavigationService.Navigate(new Uri("/SegmentDetails.xaml?id=" + ((Segment)e.AddedItems[0]).Id, UriKind.Relative));
            }
            ((ListBox)sender).SelectedIndex = -1;
        }

        private void SetSegmentOrder_Click(object sender, RoutedEventArgs e)
        {
            /*foreach (Segment seg in App.ViewModel.Segments)
            {
                System.Diagnostics.Debug.WriteLine(seg.Name + "\t" +
                                                   seg.Distance + "\t" +
                                                   seg.AverageGrade + "\t" +
                                                   seg.ElevationDifference + "\t" +
                                                   seg.MyVAM + "\t" +
                                                   seg.MyRelativePower + "\t" +
                                                   seg.MyFastestEffort.ElapsedTime + "\t" +
                                                   seg.KOMVAM + "\t" +
                                                   seg.KOMRelativePower + "\t" +
                                                   seg.KOMFastestEffort.ElapsedTime + "\t" +
                                                   seg.MyFastestEffort.Ride.Detail.Bike.Name + "\t" +
                                                   seg.ClimbCategoryOrder + "\t" +
                                                   seg.PlacingCount + "\t" +
                                                   seg.TopPlacing + "\t" +
                                                   seg.TimeDifferenceToBest);
            }*/

            App.ViewModel.SetSegmentOrder(((MenuItem)sender).Header.ToString());
        }

        private void SetRideOrder_Click(object sender, RoutedEventArgs e)
        {
            App.ViewModel.SetRideOrder(((MenuItem)sender).Header.ToString());
        }

        private void NewCourses_Click(object sender, EventArgs e)
        {
            App.ViewModel.CheckForNewCourses();
        }

        private void SegmentPlacings_Click(object sender, EventArgs e)
        {
            App.ViewModel.CheckSegmentPlacings();
        }

        private void TopSegmentPlacings_Click(object sender, EventArgs e)
        {
            App.ViewModel.CheckSegmentPlacings("Top");
        }

        private void NewSegments_Click(object sender, EventArgs e)
        {
            App.ViewModel.CheckForNewSegments();
        }

        private void Alerts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                switch (((Alert)e.AddedItems[0]).Type)
                {
                    case "Segment":
                        NavigationService.Navigate(new Uri("/SegmentDetails.xaml?id=" + ((Alert)e.AddedItems[0]).Id, UriKind.Relative));
                        break;
                }
            }
            ((ListBox)sender).SelectedIndex = -1;
        }

        private void ClearAlerts_Click(object sender, EventArgs e)
        {
            App.ViewModel.ClearAlertsCache();
        }

        GeoCoordinateWatcher watcher;

        private void Explorer_Loaded(object sender, RoutedEventArgs e)
        {
            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
                watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
                watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            }
            watcher.Start();
            //SegmentExplorerMap.
            //App.ViewModel.SegmentExplorer();
        }

        DispatcherTimer mapTimer;
        GeoCoordinate TopLeft;
        GeoCoordinate BottomRight;

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            SegmentExplorerMap.Center = e.Position.Location;
            SegmentExplorerMap.ZoomLevel = 12;

            mapTimer = new DispatcherTimer();
            mapTimer.Interval = new TimeSpan(0, 0, 0, 0, 200);
            mapTimer.Tick += new EventHandler(mapTimer_Tick);

            SegmentExplorerMap.ViewChangeOnFrame += new EventHandler<Microsoft.Phone.Controls.Maps.MapEventArgs>(SegmentExplorerMap_ViewChangeOnFrame);

            watcher.Stop();
        }

        void mapTimer_Tick(object sender, EventArgs e)
        {
            mapTimer.Stop();

            App.ViewModel.SegmentExplorer(BottomRight, TopLeft);
        }

        void SegmentExplorerMap_ViewChangeOnFrame(object sender, Microsoft.Phone.Controls.Maps.MapEventArgs e)
        {
            TopLeft = SegmentExplorerMap.ViewportPointToLocation(new Point(0, 0));
            BottomRight = SegmentExplorerMap.ViewportPointToLocation(new Point(SegmentExplorerMap.ViewportSize.Width, SegmentExplorerMap.ViewportSize.Height));

            if (mapTimer.IsEnabled)
            {
                mapTimer.Stop();
            }
            mapTimer.Start();
        }


    }
}